// uuid.ts - UUID生成工具
// @/utils/monitor/utils/uuid.ts

/**
 * 生成UUID v4
 */
export function generateUUID(): string {
  // #ifdef H5
  // 现代浏览器支持crypto.randomUUID
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    try {
      return crypto.randomUUID();
    } catch (error) {
      console.warn('[UUID] crypto.randomUUID failed, fallback to manual generation:', error);
    }
  }
  
  // 使用crypto.getRandomValues
  if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
    try {
      const array = new Uint8Array(16);
      crypto.getRandomValues(array);
      
      // 设置版本和变体位
      array[6] = (array[6] & 0x0f) | 0x40; // 版本4
      array[8] = (array[8] & 0x3f) | 0x80; // 变体
      
      return formatUUID(array);
    } catch (error) {
      console.warn('[UUID] crypto.getRandomValues failed, fallback to Math.random:', error);
    }
  }
  // #endif
  
  // 降级方案：使用Math.random
  return generateUUIDWithMathRandom();
}

/**
 * 使用Math.random生成UUID
 */
function generateUUIDWithMathRandom(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

/**
 * 格式化字节数组为UUID字符串
 */
function formatUUID(array: Uint8Array): string {
  const hex = Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
  return [
    hex.slice(0, 8),
    hex.slice(8, 12),
    hex.slice(12, 16),
    hex.slice(16, 20),
    hex.slice(20, 32)
  ].join('-');
}

/**
 * 生成短UUID（12位）
 */
export function generateShortUUID(): string {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  
  for (let i = 0; i < 12; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  
  return result;
}

/**
 * 生成数字ID
 */
export function generateNumericId(): string {
  return Date.now().toString() + Math.random().toString().slice(2, 8);
}

/**
 * 生成会话ID（基于时间戳）
 */
export function generateSessionId(): string {
  const timestamp = Date.now().toString(36);
  const random = Math.random().toString(36).substring(2, 10);
  return `session_${timestamp}_${random}`;
}

/**
 * 生成设备指纹
 */
export function generateDeviceFingerprint(): string {
  const components: string[] = [];
  
  // #ifdef H5
  if (typeof navigator !== 'undefined') {
    components.push(navigator.userAgent || '');
    components.push(navigator.language || '');
    components.push(navigator.platform || '');
    components.push(String(navigator.hardwareConcurrency || 0));
    components.push(String(navigator.deviceMemory || 0));
    
    if (typeof screen !== 'undefined') {
      components.push(`${screen.width}x${screen.height}`);
      components.push(String(screen.colorDepth || 0));
    }
    
    // 时区偏移
    components.push(String(new Date().getTimezoneOffset()));
  }
  // #endif
  
  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      const systemInfo = uni.getSystemInfoSync();
      components.push(systemInfo.platform || '');
      components.push(systemInfo.system || '');
      components.push(systemInfo.version || '');
      components.push(systemInfo.model || '');
      components.push(`${systemInfo.screenWidth}x${systemInfo.screenHeight}`);
      components.push(systemInfo.brand || '');
    } catch (error) {
      components.push('miniprogram');
    }
  }
  // #endif
  
  // 生成指纹
  const fingerprint = components.join('|');
  return hashString(fingerprint);
}

/**
 * 简单哈希函数
 */
function hashString(str: string): string {
  let hash = 0;
  if (str.length === 0) return hash.toString();
  
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // 转换为32位整数
  }
  
  return Math.abs(hash).toString(36);
}

/**
 * 验证UUID格式
 */
export function isValidUUID(uuid: string): boolean {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(uuid);
}

/**
 * 生成带前缀的ID
 */
export function generateIdWithPrefix(prefix: string): string {
  return `${prefix}_${generateShortUUID()}_${Date.now()}`;
}

/**
 * 生成请求ID
 */
export function generateRequestId(): string {
  return generateIdWithPrefix('req');
}

/**
 * 生成跟踪ID
 */
export function generateTraceId(): string {
  return generateIdWithPrefix('trace');
}

/**
 * 获取设备ID（持久化）
 */
export function getDeviceId(): string {
  const key = 'monitor_device_id';
  
  // #ifdef H5
  if (typeof localStorage !== 'undefined') {
    let deviceId = localStorage.getItem(key);
    if (!deviceId) {
      deviceId = generateIdWithPrefix('device');
      localStorage.setItem(key, deviceId);
    }
    return deviceId;
  }
  // #endif
  
  // #ifdef MP
  if (typeof uni !== 'undefined') {
    try {
      let deviceId = uni.getStorageSync(key);
      if (!deviceId) {
        deviceId = generateIdWithPrefix('device');
        uni.setStorageSync(key, deviceId);
      }
      return deviceId;
    } catch (error) {
      return generateIdWithPrefix('device');
    }
  }
  // #endif
  
  // 降级方案
  return generateIdWithPrefix('device');
} 